<template>
  <el-dialog @close="close" v-model="dialogVisible" width="650">
    <template #title>
      <span class="el-dialog__title">{{ title }}</span>
    </template>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px">
      <el-form-item label="上级部门" prop="parentId">
        <el-tree-select
          ref="treeRef"
          v-model="ruleForm.parentId"
          :data="deptOptions"
          placeholder="请选择上级部门"
          check-strictly
          clearable
          value-key="value"
          :default-expanded-keys="[ruleForm.parentId]"
          highlight-current
          style="width: 100%"
        >
          <template #default="{ data: { label, length } }">
            {{ label }}
            <span style="color: gray" v-if="length > 0"> ({{ length }}) </span>
          </template>
        </el-tree-select>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="部门名称" prop="deptName">
            <el-input v-model="ruleForm.deptName" placeholder="请输入部门名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示排序" prop="orderNum">
            <el-input-number v-model="ruleForm.orderNum" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="负责人" prop="leader">
            <el-input v-model="ruleForm.leader" placeholder="请输入负责人" maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="ruleForm.phone" placeholder="请输入联系电话" maxlength="11" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="ruleForm.email" placeholder="请输入邮箱" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门状态">
            <el-radio-group v-model="ruleForm.status">
              <el-radio
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注">
        <el-input v-model="ruleForm.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="success" @click="submitForm">提交</el-button>
        <el-button type="warning" @click="dialogVisible = false">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
  import { ElMessageBox, ElMessage, FormInstance } from 'element-plus'
  import { getCurrentInstance, reactive, ref } from 'vue'
  import { deptData } from '@/mock/system'
  import { reqDeptAddUrl, reqDeptEditUrl, reqDeptExcludeUrl } from '@/api/system/dept'
  import { NodeType } from '@/api/system/menu/type'

  const ruleFormRef = ref<FormInstance>()
  const dialogVisible = ref<boolean>(false)
  const deptOptions = ref() /*部门数据*/
  const title = ref('新增部门')
  const { proxy }: any = getCurrentInstance()
  let $emit = defineEmits(['getList'])

  const deptProps = {
    value: 'id',
    label: 'deptName',
    checkStrictly: true,
  }

  /*进行表单校验*/
  const rules = reactive({
    parentId: [{ required: true, message: '上级部门不能为空', trigger: 'change' }],
    deptName: [{ required: true, message: '部门名称不能为空', trigger: 'change' }],
    orderNum: [{ required: true, message: '显示顺序不能为空', trigger: 'change' }],
    email: [
      {
        type: 'email',
        message: '请输入正确的邮箱地址',
        trigger: ['blur', 'change'],
      },
    ],
    phone: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur',
      },
    ],
  })

  const ruleForm = reactive({
    deptName: '',
    deptId: '',
    parentId: 0,
    orderNum: '0',
    leader: null,
    phone: null,
    email: null,
    status: '0',
    remark: null,
  })

  const handleDialogValue = async (deptId: any) => {
    await reqDeptExcludeUrl(deptId)
      .then((req) => {
        console.log('req', req)
        deptOptions.value = filterMethod(proxy.$handleTree(req.data, 'deptId'))
      })
      .catch((e) => {
        ElMessage.error('获取上级部门树失败！')
      })
  }

  const show = async (item: any = {}) => {
    title.value = '新增部门'

    await handleDialogValue(item.deptId || -1)
    if (item.deptId) {
      title.value = '编辑部门'
      Object.keys(item).forEach((key) => {
        ruleForm[key] = item[key]
      })
    } else {
      ruleForm.parentId = item.parentId
    }

    dialogVisible.value = true
  }

  /*生成节点树*/
  const filterMethod = (options) => {
    let list: NodeType[] = []
    ;[...options].filter((item: any) => {
      let node: NodeType = {
        value: 0,
        label: '',
        length: 0,
        children: [],
      }
      node.value = item.deptId
      node.label = item.deptName
      node.length = item.children.length == undefined ? 0 : item.children.length
      if (item.children) {
        node.children = getChildMethod(item.children)
      }
      list.push(node)
    })
    return [
      {
        value: 0,
        label: '主类目',
        children: list,
      },
    ]
  }
  const getChildMethod = (item: any) => {
    let child: any = []
    item.filter((it: any) => {
      const node = ref({
        value: undefined,
        length: undefined,
        label: null,
        children: [],
      })
      node.value.value = it.deptId
      node.value.label = it.deptName
      node.value.length = it.children.length
      if (it.children) {
        node.value.children = getChildMethod(it.children)
      }
      child.push(node)
    })
    return child
  }

  const submitForm = async (done: () => void) => {
    await ruleFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        let result = null
        if (!ruleForm.deptId) {
          result = await reqDeptAddUrl(ruleForm)
        } else {
          result = await reqDeptEditUrl(ruleForm)
        }
        if (result.code === 200) {
          ElMessage.success(result.message == null ? '添加成功' : result.message)
          dialogVisible.value = false
          $emit('getList')
          close() /*关闭对话框*/
        } else {
          ElMessage.error(result.message == null ? '操作失败' : result.message)
        }
      } else {
        console.log('error submit!', fields)
      }
    })
  }

  /*关闭对话框得到回调函数*/
  function close() {
    ruleFormRef.value.resetFields()
    Object.keys(ruleForm).forEach((key) => {
      if (key === 'parentId') ruleForm[key] = 0
      else if (key === 'orderNum') ruleForm[key] = '0'
      else if (key === 'status') ruleForm[key] = '0'
      else ruleForm[key] = null
    })
  }

  defineExpose({
    show,
  })
</script>

<script lang="ts">
  export default {
    dicts: ['sys_normal_disable'],
  }
</script>
<style lang="scss" scoped>
  @import './../index';
</style>
